<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\event;

use app\library\redis\Redis;
use app\library\websocket\logic\{Sessions, Users};
use app\library\websocket\tool\{MessageBuilder, Pusher};
use Swoole\Http\Request;
use Swoole\WebSocket\Server;

class OpenEvent
{
	public static function handle(Server $server, Request $request)
	{
		$userToken = $request->cookie['token'] ?? '';
		if (empty($userToken)) {
			(new Pusher($server))->from($request->fd)->notice((new MessageBuilder(true))->write('缺少身份信息'));
			return;
		}

		$redis = Redis::get();
		$userId = $redis->get($userToken);

		if (!$userId) {
			$builder = (new MessageBuilder(true, MessageBuilder::FORBIDDEN))->write('用户信息不存在，您即将下线');
			(new Pusher($server))->from($request->fd)->notice($builder);
			return;
		}

		$userInfo = Users::getUserById($userId);
		if (!$userInfo) {
			$builder = (new MessageBuilder(true, MessageBuilder::FORBIDDEN))->write('用户信息不存在，您即将下线');
			(new Pusher($server))->from($request->fd)->notice($builder);
			return;
		}
		$userInfo['token'] = $userToken;

		/**
		 * 根据identity获取原fd判断客户端是否重连如果重连需要无感切换
		 * 如果重连 则清除原有fd相关联的所有用户信息
		 *
		 * 根据加密fd_$userId存储了fd
		 * 根据加密user_id_$fd存储了userid
		 * 根据加密userId存储了UserInfo
		 *
		 */
		$originalFd = Users::getFd($userId);

		if ($request->fd != $originalFd) {
			Users::clearUserByfd($originalFd);
			Users::setUser($request->fd, $userId, $userInfo);
		} else {
			if (!Users::exists($request->fd, $userId)) {
				Users::clearUserByfd($originalFd);
				Users::setUser($request->fd, $userId, $userInfo);
			}
		}

		unset($userInfo['user_id']);
		$data = [
			'user_info'  => $userInfo,
			'config'     => config('front'),
			'chat_group' => Sessions::getUsersSessionList($userId),
			'friends'    => []
		];
		$message = (new MessageBuilder(false, 'login'))->write('连接成功', 200, $data);
		#TODO:读取群组信息、好友信息、会话信息
		(new Pusher($server))->from($request->fd)->notice($message);
	}
}
